
package com.cy.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public abstract class BaseAction extends ActionSupport {

public abstract String execute();
	protected String returnMsg;	//返回页面提示信息
	protected String backURL;	//返回页面URL
	
	public String getBackURL2(String code) {
		try {
			HttpServletRequest r = ServletActionContext.getRequest();

			String query = "";
			String uri = r.getRequestURI();

			// if (r.getMethod().equalsIgnoreCase("POST")) {
			ActionContext c = ActionContext.getContext();
			Map m = c.getParameters();

			query = "?testbyshark=1";

			for (Iterator iter = m.keySet().iterator(); iter.hasNext();) {
				Object param = iter.next();
				if (param == null) {
					continue;
				}

				Object v = m.get(param);

				if ("testbyshark".equals(param.toString())) {
					continue;
				}

				// append
				if (v instanceof Object[]) {
					query = query + extractToStringBuffer(param, v);
				} else {
					query = query + "&";

					query = query + param.toString();
					query = query + "=";
					query = query + v.toString();
				}
			}

			uri = uri + query;

			/*
			 * } else if (r.getMethod().equalsIgnoreCase("GET")) { query =
			 * r.getQueryString(); if (!Validator.isEmpty(query)) { uri = uri +
			 * "?" + query; } }
			 */
			if (StringUtils.isNotEmpty(code)) {
				return URLEncoder.encode(uri, code);
			} else {
				return uri;
			}

		} catch (Exception ex) {
			return "";
		}
	}
	private String extractToStringBuffer(Object param, Object values)
			throws UnsupportedEncodingException {
		String sb = "";

		Object[] objs = (Object[]) values;
		if (objs == null)
			return "";
		if (objs.length == 0)
			return "";

		for (int i = 0; i < objs.length; i++) {
			if (StringUtils.isNotEmpty(objs[i].toString())){
				sb = sb + "&";
				sb = sb + param.toString();
				sb = sb + "=";
				Object v = objs[i];
	
				sb = sb + v.toString();
			}

		}

		return sb;
	}
	
	//页面返回信息构造方法
	protected void parseReturnInfo(String returnMsg,String backURL){
		this.returnMsg=returnMsg;
		this.backURL= backURL;
	}
	public String getRootURL() {
		return ServletActionContext.getRequest().getContextPath();
	}
	
	
	
	public String getBackURL() {
		return backURL;
	}
	public void setBackURL(String backURL) {
		this.backURL = backURL;
	}
	public String getReturnMsg() {
		return returnMsg;
	}
	public void setReturnMsg(String returnMsg) {
		this.returnMsg = returnMsg;
	}
	
	
	
}
